package fms.models;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import fms.classes.User;
 
 
public class UserDAO {
 
    private SqlSessionFactory sqlSessionFactory;
 
    public UserDAO(){
    	try {
    		sqlSessionFactory = MyBatisSqlConnection.getSqlSessionFactory();
    	} catch(Exception e){
    		System.out.println("failed to get sqlSessionFactory");
    	}
    }
 
    /**Returns the list of all User instances from the database*/
    @SuppressWarnings("unchecked")
    public List<User> selectAll(){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            List<User> list = session.selectList("User.getAll");
            return list;
        } finally {
            session.close();
        }
    }
 
    /**Returns a User instance from the database*/
    public User selectById(int user_id){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            User user = (User) session.selectOne("User.getByuser_id",user_id);
            return user;
        } finally {
            session.close();
        }
    }
 
    /**Updates an instance of User in the database*/
    public void update(User user){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            session.update("User.update", user);
            session.commit();
        } finally {
            session.close();
        }
    }
 
    /** Insert an instance of User into the database*/
    public void insert(User user){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            session.insert("User.insert", user);
            session.commit();
        } finally {
            session.close();
        }
    }
 
    /** Delete an instance of User from the database*/
    public void delete(int user_id){
 
        SqlSession session = sqlSessionFactory.openSession();
 
        try {
            session.delete("User.deleteById", user_id);
            session.commit();
        } finally {
            session.close();
        }
    }
}